package top.ljlgithub.api.controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.ljlgithub.api.bean.UploadParam;
import top.ljlgithub.api.common.response.Meta;
import top.ljlgithub.api.common.response.ResponseEntity;
import top.ljlgithub.api.exception.ParamException;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.UUID;

/**
 * @ClassName文件上传
 * @Description TODO
 * @Author L1470
 * @Date 2021/5/8 15:44
 * @Version 1.0
 **/
@CrossOrigin
@RestController
public class FileController {
    @PostMapping(value = "/upload")
    public ResponseEntity fileUpload(MultipartFile file, HttpServletRequest request) throws ParamException, FileNotFoundException {
        if (file.isEmpty()) {
            throw new ParamException("文件不能为空");
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String path = ResourceUtils.getURL("classpath:").getPath();
        String absolutePath = new File(path, "static/tmp_uploads/").getAbsolutePath();
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(absolutePath + "\\" + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String tmp_path = "/tmp_uploads/" + fileName;
        String url = "https://www.gaborder.top:442" + request.getContextPath() + tmp_path;
        HashMap<String, String> map = new HashMap<>();
        map.put("tmp_path",tmp_path);
        map.put("url",url);
        Meta meta = new Meta("上传成功", 200);
        ResponseEntity<Object> result = new ResponseEntity<>(map,meta);
        return result;
    }

}